﻿namespace TomatoBreak.IntegrationSpecs
{
    using System;
    using System.IO;

    using Machine.Specifications;

    public class Bootstrapper : IAssemblyContext
    {
        private static readonly string databaseFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database.sdf");

        public void OnAssemblyStart()
        {
            DeleteDatabase();
            CreateDatabase();
        }

        public void OnAssemblyComplete()
        {
            DeleteDatabase();
        }

        private static void CreateDatabase()
        {
            var databaseStream = typeof(Bootstrapper).Assembly.GetManifestResourceStream(typeof(Bootstrapper).Namespace + ".database.sdf");

            if (databaseStream == null)
            {
                throw new InvalidOperationException("Unable to find the database in the assembly resource.");
            }

            using (var fileStream = File.OpenWrite(databaseFilePath))
            {
                databaseStream.CopyTo(fileStream);
                fileStream.Flush();
            }

            File.SetAttributes(databaseFilePath, FileAttributes.Normal);
        }

        private static void DeleteDatabase()
        {
            if (File.Exists(databaseFilePath))
            {
                //File.Delete(databaseFilePath);
            }
        }
    }
}